package me.ahoukuse.capturedemov1;

import java.util.Arrays;

public class Packet {
    private final static int HEAD_SIZE = 16; //In size;
    private int packet_id;
    private int totalLength;
    private int offset;
    private int dataLength;
    private byte[] data;

    public Packet(int pac_id, int off, byte[] d) {
        packet_id = pac_id;
        offset = off;
        data = d;
    }
    public Packet() {}

    public void setData(byte[] data) {
        this.data = data;
    }

    public void setTotalLength(int totalLength) {
        this.totalLength = totalLength;
    }

    public void setDataLength(int dataLength) {
        this.dataLength = dataLength;
    }

    public int getTotalLength() {
        return totalLength;
    }

    public int getDataLength() {
        return dataLength;
    }

    public void setOffset(int offset) {
        this.offset = offset;
    }

    public void setPacket_id(int packet_id) {
        this.packet_id = packet_id;
    }

    public byte[] getData() {
        return data;
    }

    public int getOffset() {
        return offset;
    }

    public int getPacket_id() {
        return packet_id;
    }
    //大端序
    private byte[] toBytes(int x) {
        byte[] b = new byte[4];
        b[0] = (byte) (x & 0xFF);
        b[1] = (byte) (x >> 8 & 0xFF);
        b[2] = (byte) (x >> 16 & 0xFF);
        b[3] = (byte) (x >> 24);
        return b;
    }
    public byte[] getBytes() {
        byte[] bytes = new byte[data.length + HEAD_SIZE];
        byte[] pacBytes = toBytes(packet_id);
        byte[] totalLengthBytes = toBytes(totalLength);
        byte[] offsetBytes = toBytes(offset);
        byte[] dataLengthBytes = toBytes(dataLength);
        int idx = 0;
        for (byte pacByte : pacBytes) {
            bytes[idx++] = pacByte;
        }
        for (byte totalLengthByte : totalLengthBytes) {
            bytes[idx++] = totalLengthByte;
        }
        for (byte offsetByte : offsetBytes) {
            bytes[idx++] = offsetByte;
        }
        for (byte dataLengthByte : dataLengthBytes) {
            bytes[idx++] = dataLengthByte;
        }
        for (byte dataByte : data) {
            bytes[idx++] = dataByte;
        }
        return bytes;
    }
    public int getPacketLength() {
        return data.length + HEAD_SIZE;
    }
}
